<template>
  <!-- 页面-维度管理-设置 -->
  <div class="innerPageTable-box-Three dimension-data-manage-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 维度编码 -->
          <Form-item :label="$t('module.dimension.dimensionCode')">
            <Input type="text" v-model="dimension.dimensionCode" disabled />
          </Form-item>

          <!-- 维度名称 -->
          <Form-item :label="$t('module.dimension.dimensionName')">
            <Input type="text" v-model="dimension.dimensionName" disabled />
          </Form-item>

          <!-- 所属产品 -->
          <!-- <Form-item :label="$t('module.valueSet.ownnerproduct')">
                <Input type="text" v-model="dimension.productId"  disabled />
        </Form-item>-->
        </template>
      </Form>
    </SelfAdaption>

    <InnerPageTable ref="dataSourceTable" :config="tableConfig">
      <div slot="table-bar">
        <RPButton optType="create" @click="addOrEditDataSource({})" />
        <RPButton optType="batch" @click="deleteDataSource" />
      </div>
    </InnerPageTable>
  </div>
</template>
<script>
import { delDimensionDataSource, getDimenionData } from '@/api/dimensionApi.js'
import { sourceColumns } from './columns.js'
import DataSourceEdit from './DimensionDataSourceEdit'
import previewDataSource from './previewDataSource'
import locales from './locales.js'
import tenantAPI from '@/api/tenantApi.js'

export default {
  name: 'datasourcelist',
  mixins: [locales],
  data: () => ({
    tenantList: [],
    searchForm: {},
    listTotal: 0
  }),
  props: {
    tenantCode: {
      type: String,
      default: ''
    },
    dimension: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: this.getDimensionDataSourceList,
        columnsFn: sourceColumns.bind(this),
        initParam: { dimensionId: this.dimension.id, tenantCode: this.tenantCode },
        autoFirst: false
      }
    },
    hidePreviewBtn() {
      // 针对特定类型隐藏预览按钮
      if (this.dimension?.dataStructType === 99) {
        return true
      }
      return false
    }
  },
  created() {
    this.$emit('setTitle', this.$t('module.dimension.dataSourceManage'))
    this.initTenant()
  },
  methods: {
    previewDataSource(dataSource) {
      new this.$pageModal(
        previewDataSource,
        {
          props: {
            dataStructType: this.dimension.dataStructType,
            dimensionDataUrl: dataSource.dimensionDataUrl
          }
        },
        data => {
          if (data) this.search()
        }
      )
    },
    // 数据源分页列表查询
    getDimensionDataSourceList({ responseProcess, param }) {
      $http.post(`${window.RPConfig.mgt}/dimensionDataUrl/list/page`, param).then(res => {
        // 状态为有效：禁用复选框，不可删除
        let { records } = res.data
        this.listTotal = res.data.total
        records = this.$root.$options.filters['selection-disabled'](records)
        responseProcess(res.data)
      })
    },
    // 初始化所属租户
    initTenant() {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          this.tenantList[tenant.tenantCode] = tenant.tenantName
        }
        this.search()
      })
    },
    getTenantName(tenantCode) {
      if (tenantCode) {
        return this.tenantList[tenantCode] ? this.tenantList[tenantCode] : tenantCode
      }
      return tenantCode
    },
    search(page) {
      this.$refs['dataSourceTable'].load(this.searchForm, page)
    },
    addOrEditDataSource(dataSource) {
      if (Object.keys(dataSource).length == 0 && this.listTotal > 0) {
        this.$message.error({
          content: this.$t('module.dimension.warning.isOnlyCreatData'),
          duration: 3
        })
        return
      }
      new this.$pageModal(
        DataSourceEdit,
        {
          props: {
            dimension: this.dimension,
            tenantCode: this.tenantCode,
            dataSourceId: dataSource.id
          }
        },
        data => {
          if (data) this.search()
        }
      )
    },
    deleteDataSource() {
      let selectedIds = this.getSelectedIds()
      if (selectedIds.length == 0) {
        this.$message.error({
          content: this.$t('module.dimension.warning.selectDataSource'),
          duration: 3
        })
        return
      }
      new $confirm(`${this.$t('common.confirmDeletion')}`, this).then(() => {
        // $store
        //   .dispatch("DeleteDimensionDataSource", selectedIds)
        delDimensionDataSource(selectedIds)
          .then(res => {
            this.$message.success({
              content: this.$t('module.dimension.warning.deleteDataSourceSuccessfully'),
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    getSelectedIds() {
      let list = this.$refs['dataSourceTable'].getSelectioned() || []
      return list.map(l => l.id)
    }
  }
}
</script>
